//
//  SportVM.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/6/30.
//


import RxSwift
import Combine
import Moya

class SportVM: ObservableObject {
    @Published var pageNum: Int = 1
    @Published var pageSize: Int = 10
    @Published var isLoading = false
    @Published var error: String?
    @Published var isSuccess = false
    @Published var listModel: FitnesslistResponse?
    
    private let disposeBag = DisposeBag()
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        getFitnessList()
    }
    
    private func setupBindings() {
        $pageNum
            .combineLatest($pageSize)
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
            .sink { [weak self] _ in
                self?.getFitnessList()
            }
            .store(in: &cancellables)
    }
    
    func getFitnessList() {
        isLoading = true
        error = nil
//        NetworkManager.shared.fitnessList()
//            .observe(on: MainScheduler.instance)
//            .subscribe(
//                onSuccess: { [weak self] response in
//                    self?.handleSuccess(response)
//                },
//                onFailure: { [weak self] error in
//                    self?.handleError(error)
//                }
//            )
//            .disposed(by: disposeBag)
        NetworkManager.shared.request(MultiTarget(ApiService.fitnessList), responseType: FitnesslistResponse.self)
            .observe(on: MainScheduler.instance)
            .subscribe(
                onNext: { [weak self] response in
                    self?.handleSuccess(response)
                },
                onError: { [weak self] error in
                    self?.handleError(error)
                }
            )
            .disposed(by: disposeBag)
    }
    
    private func handleSuccess(_ response: FitnesslistResponse) {
        isLoading = false
        isSuccess = true
        listModel = response
    }
    
    private func handleError(_ error: Error) {
        isLoading = false
        isSuccess = false
        if let networkError = error as? NetworkError {
            self.error = networkError.errorDescription
//            if networkError.isAuthenticationError {
//                AppState.shared.logout()
//            }
        } else {
            self.error = error.localizedDescription
        }
    }
    
    func refresh() {
        pageNum = 1
    }
    
    func loadMore() {
        pageNum += 1
        getFitnessList()
    }
}
